<?php
    require_once 'google-api-php-client/autoload.php';
    require_once 'facebook-php-sdk-v4-4/autoload.php';       
    require_once 'facebook-php-sdk-v4-4/src/Facebook/FacebookSession.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/FacebookRequest.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/FacebookResponse.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/GraphObject.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/GraphUser.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/FacebookSDKException.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/FacebookRequestException.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/FacebookRedirectLoginHelper.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/FacebookAuthorizationException.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/GraphSessionInfo.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/Entities/AccessToken.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/HttpClients/FacebookCurl.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/HttpClients/FacebookCurlHttpClient.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/HttpClients/FacebookGuzzleHttpClient.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/HttpClients/FacebookHttpable.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/HttpClients/FacebookStream.php';
    require_once 'facebook-php-sdk-v4-4/src/Facebook/HttpClients/FacebookStreamHttpClient.php';
    require_once 'google-api-php-client/src/Google/Client.php';
    require_once 'google-api-php-client/src/Google/Service.php';

    use Facebook\FacebookSession;
    use Facebook\FacebookRedirectLoginHelper;
    use Facebook\FacebookRequest;
    use Facebook\FacebookResponse;
    use Facebook\FacebookSDKException;
    use Facebook\FacebookRequestException;
    use Facebook\FacebookAuthorizationException;
    use Facebook\GraphObject;
    use Facebook\GraphUser;
    use Facebook\GraphSessionInfo;
    use Facebook\FacebookHttpable;
    use Facebook\FacebookCurlHttpClient;
    use Facebook\FacebookCurl;
    session_start();
class AppController extends Controller{
	public function actionFblogin(){
        if(!isset(Yii::app()->session['_LOGGED_USER'])){
            $app_id = '831641436876317';
            $app_secret = '6a4304cc0acd9e1171819adb4704590d';
            $redirect_url = 'http://yardsale.local/app/fblogin';
            FacebookSession::setDefaultApplication($app_id, $app_secret);
            $helper = new FacebookRedirectLoginHelper($redirect_url);
            try {
                $session = $helper->getSessionFromRedirect();
            } catch(FacebookRequestException $ex) {
                  echo 'Error login';
            } catch(\Exception $ex) {
                  echo 'Login faild';
            }
            if (isset($session)) {
                $request = new FacebookRequest($session, 'GET', '/me');
                $response = $request->execute();
                $graph = $response->getGraphObject(GraphUser::classname());
                $checkUser = Users::model()->findByAttributes(array('facebook_id' => $graph->getId()));
                if(!$checkUser){
                    Yii::app()->session['fb_token'] = $session->getToken();
                    $user = new Users;
                    $user['facebook_id'] = $graph->getId();
                    $user['birthday'] = $graph->getProperty('birthday');
                    $user['email'] = $graph->getProperty('email');
                    $user['first_name'] = $graph->getFirstname();
                    $user['gender'] = $graph->getProperty('gender');
                    $user['last_name'] = $graph->getLastname();
                    $user['created_date'] = time();
                    $user['application_id'] = 2;
                    $user['role_id'] = 2;
                    $user['status'] = 1;
                    //$user['photo'] = 'https://graph.facebook.com/' . $id . '/picture?width=100';

                    if($user->save()){
                        Yii::app()->session['_LOGGED_USER'] = $user;
                    }
                        //$user['link'] = https://www.facebook.com/app_scoped_user_id/699803353426433/
                        //$user[locale] => en_GB
                        //$user[name] => Tap Nguyen
                        //$user[timezone] => 7
                        //$user[updated_time] => 2014-02-13T00:39:15+0000
                        //$user[verified] => 1
                }else{
                    Yii::app()->session['_LOGGED_USER'] = $checkUser;
                }                    
                //$this->redirect(Yii::app()->createAbsoluteUrl('app/profile'));
                $this->redirect('/');
            }else{
                $this->redirect($helper->getLoginUrl(array('email')));
            }
        }else{
            $this->redirect('/');
        }
    }

    public function actionGglogin(){
        if (isset($_GET['state']) && $_SESSION['state'] != $_GET['state']) {
          header('HTTP/ 401 Invalid state parameter');
          exit;
        }

        $client = new Google_Client();
        $client->setApplicationName('Google+ server-side flow');
        $client->setClientId('93562038814-sa9ih1muinpmvlnbd31dpeel665c7gar.apps.googleusercontent.com');
        $client->setClientSecret('HMLGF5soV0PIuOSbSJRXCUH2');
        $client->setRedirectUri('http://test.searchyardsale.net/app/gglogin');
        $client->setDeveloperKey('AIzaSyB9Q7E1DSpxqLs4ipFTTBequPbzHRquSlM');
        $plus = new Google_PlusService($client);

        if (isset($_GET['code'])) {
          $client->authenticate();
          // Get your access and refresh tokens, which are both contained in the
          // following response, which is in a JSON structure:
          $jsonTokens = $client->getAccessToken();
          $_SESSION['token'] = $jsonTokens;

          // Store the tokens or otherwise handle the behavior now that you have
          // successfully connected the user and exchanged the code for tokens. You
          // will likely redirect to a different location in your app at thsi point.
          $redirect = 'http://test.searchyardsale.net';
          header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
        }

    }
}